package com.jf.cloud.common.handler;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class GracefulShutdown implements ApplicationListener<ContextClosedEvent> {

    private static final Logger log = LoggerFactory.getLogger(GracefulShutdown.class);
    @Autowired
    private NacosAutoServiceRegistration serviceRegistration;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.info("开始服务下线");
        serviceRegistration.stop();
        log.info("完成服务下线，等待30秒关闭响应");

        int wait = 30;
        int num = 0;
        while (true) {
            try {
                //等待客户端刷新服务发现列表
                TimeUnit.SECONDS.sleep(1);
                num++;
                log.info("还需等待{}秒",wait - num);
                if (num >= wait) {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
